using System;
using System.Windows.Forms;

using ADODB;
using MSDASC;


namespace FinlogiK.FxCop.Statistics.Windows
{
	internal sealed class ConnectionStringDialog : CommonDialog
	{
		#region Fields

		private string _connectionString;
		private string _defaultProvider;
		private bool _stripDefaultProvider;

		#endregion

		#region Constructors

		internal ConnectionStringDialog()
			: base()
		{
			this.Reset();
		}

		#endregion

		#region Properties

		internal string ConnectionString
		{
			get
			{
				return this._connectionString;
			}
			set
			{
				this._connectionString = (value ?? string.Empty);
			}
		}

		internal string DefaultProvider
		{
			get
			{
				return this._defaultProvider;
			}
			set
			{
				this._defaultProvider = value ?? string.Empty;
			}
		}

		internal bool StripDefaultProvider
		{
			get
			{
				return this._stripDefaultProvider;
			}
			set
			{
				this._stripDefaultProvider = value;
			}
		}

		#endregion

		#region Methods

		public override void Reset()
		{
			this.ConnectionString = string.Empty;
			this.DefaultProvider = "SQLNCLI.1";
			this.StripDefaultProvider = true;
		}

		protected override bool RunDialog(IntPtr hwndOwner)
		{
			string connectionString = this.ConnectionString;
			if (string.IsNullOrEmpty(connectionString))
			{
				connectionString = "Provider=" + this.DefaultProvider;
			}
			else
			{
				connectionString = ";" + connectionString + ";";
				if (!connectionString.Contains(";Provider="))
				{
					connectionString += "Provider=" + this.DefaultProvider;
					connectionString = connectionString.Trim(';');
				}
			}

			Connection connection = new Connection();
			connection.ConnectionString = connectionString;
			object connectionObject = (object)connection;

			DataLinks dialog = new DataLinks();
			dialog.hWnd = hwndOwner.ToInt32();
			bool result = dialog.PromptEdit(ref connectionObject);

			if (result)
			{
				connectionString = connection.ConnectionString;
				if (this.StripDefaultProvider)
				{
					connectionString = ";" + connectionString.Trim() + ";";
					connectionString = connectionString.Replace(";Provider=" + this.DefaultProvider + ";", ";");
					connectionString = connectionString.Trim(';');
				}

				this.ConnectionString = connectionString;
			}

			return result;
		}

		#endregion
	}
}